package com.example.cunion.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.cunion.common.R;
import com.example.cunion.controller.form.AddDishForm;
import com.example.cunion.controller.form.DishForm;
import com.example.cunion.controller.form.PageFom;
import com.example.cunion.entity.Dish;
import com.example.cunion.service.DishService;
import com.example.cunion.util.StringSnowflakeIdGenerator;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Resource
    private DishService dishService;

    @PostMapping("/searchDishesByShopId")
    public R searchDishesByShopId(@RequestHeader("token") String token, @RequestBody DishForm dishForm){
        //获取传入的shopId
        String shopId = dishForm.getShopId();
        //获取传入的起始位置
        Integer start = dishForm.getStart();
        //获取传入的每页长度
        Integer length = dishForm.getLength();
        //计算起始位置
        start = (start - 1) * length;
        //创建HashMap
        HashMap<String, Object> map = new HashMap<>();
        //将shopId放入HashMap
        map.put("start", start);
        map.put("length", length);
        map.put("shopId", shopId);
        //调用dishService的searchDishesByShopId方法，传入map，获取返回值
        List<HashMap> maps = dishService.searchDishesByShopId(map);
        //返回结果
        return R.ok().put("result", maps);
    }

    @PostMapping("/addDish")
    public R addDish(@RequestHeader("token") String token, @RequestBody AddDishForm form){
        StringSnowflakeIdGenerator generator = new StringSnowflakeIdGenerator(1, 1);
        String id = generator.nextId();
        form.setId(id);
        Map<String, Object> map = BeanUtil.beanToMap(form);
        Integer result = dishService.addDish((HashMap) map);
        return R.ok();
    }

    @PostMapping("/addDishByMp")
    public R addDishByMp(@RequestHeader("token") String token, @RequestBody Dish dish) {
        dishService.addDish(dish);
        return R.ok();
    }

    @GetMapping("/deleteDishByMp")
    public R deleteDishByMp(@RequestHeader("token") String token, @RequestParam("dishId") String dishId) {
        dishService.deletedDish(dishId);
        return R.ok();
    }
    @PostMapping("/updateDishByMp")
    public R updateDishByMp(@RequestHeader("token") String token, @RequestBody Dish dish) {
        dishService.updateDish(dish);
        return R.ok();
    }
    @PostMapping("/searchDishByMp")
    public R searchDishByMp(@RequestHeader("token") String token, @RequestBody PageFom form){
        List<Dish> list = dishService.searchDish(form.getStart(), form.getLength());
        return R.ok().put("result", list);
    }

}
